package com.example.flutter_native_map;

import static android.webkit.WebView.setWebContentsDebuggingEnabled;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocationClient;

import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
import com.amap.api.maps.AMapWrapper;

public class NativeMapViewFactory extends PlatformViewFactory {
    private final MapCallback mapCallback;
    public NativeMapViewFactory(MapCallback mapCallback) {
        super(StandardMessageCodec.INSTANCE);
        this.mapCallback=mapCallback;
    }
    @NonNull
    @Override
    public PlatformView create(Context context, int viewId, @Nullable Object args) {
        WebView webView=new WebView(context);
        createWeb(webView);
        loadMap(webView,context);
        return new PlatformView(){
            @NonNull
            @Override
            public View getView() {
                return webView;
            }
            @Override
            public void dispose() {}
        };
    }

    private void createWeb(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setDefaultTextEncodingName("utf-8");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setWebContentsDebuggingEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        settings.setAllowFileAccess(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
        }
        settings.setAllowContentAccess(true);
        settings.setDatabaseEnabled(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        webView.setWebChromeClient(new WebChromeClient());
    }
    private void loadMap(WebView webView, Context context) {
        AMapWrapper aMapWrapper = new AMapWrapper(context, new MAWebViewWrapper(webView));
        aMapWrapper.onCreate();
        aMapWrapper.getMapAsyn(mapCallback::onCreateView);
        AMapLocationClient.updatePrivacyAgree(context,true);
        AMapLocationClient.updatePrivacyShow(context,true,true);
    }
}
